<?php

declare(strict_types=1);

namespace App\Common\Libary\Third;

use function Hyperf\Collection\data_get;

class Jd
{
    protected string $jd_app_key = '9d7c76b7fe819964051e54f692995fb5';
    protected string $jd_app_secret = '680f7e9d80c742f5952b6bd85e9da83c';

    protected $externalInfo;

    /**
     * 礼金key
     */
    protected $giftCouponKey;

    protected $pid ;

    protected $accessToken;

    protected $sceneId;

    protected $giveUpNumberId = false;

    /**
     * 获取工具商tool
     * @return \JdTopClient
     */
    private function _get_tool_union_top(){
        vendor('jd.JdTopClient');
        vendor('jd.ResultSet');
        vendor('jd.RequestCheckUtil');
        $top            = new \JdTopClient;
        $top->appkey = $this->jd_app_key;
        $top->secretKey = $this->jd_app_secret;
        return $top;
    }

    /**
     * 根据关键词搜索京东商品
     * @param $keyword
     * @param $p
     * @param $param
     * @return mixed
     */
    public function search($keyword , $p=1, $param = []){
        $this->getSceneFromUrl($keyword);

        if($this->sceneId == 2 && !$this->giveUpNumberId){
            return container()->get(DaiMengJia::class)->searchJdItem($keyword,$p);
        }

        $jd_top = $this->_get_tool_union_top();
        $param['method'] = 'jd.union.open.goods.query';
        $keyword && $param['goodsReqDTO']['keyword'] = $keyword;
        $param['goodsReqDTO']['pageIndex'] = $p;
        $param['goodsReqDTO']['sceneId'] = $this->sceneId;
        $res = $jd_top->execute($param);
        $res = objtoarr($res);
        $res =json_decode($res['queryResult'],true);
        return $res['data'];
    }

    /**
     * 京喜团商品转链接
     * @param $url
     * @param $chainTransformType
     * @param $roleType
     * @return mixed
     */
    public function transformJx($url,$chainTransformType = 1,$roleType = 1){
        $jd_top = $this->_get_tool_union_top();
        $param['method'] = 'jingdong.jxPromoterGenerateUrl';

        if(is_numeric($url)){
            $param['sku'] = $url;
        }elseif (strpos($url, "#小程序://京喜")!==false){
            $param['wxTextChain'] = $url;
        }else {
            $param['path'] = $url;
        }
        $param['chainTransformType'] = $chainTransformType;
        $param['bizCode'] = (string)$this->externalInfo;
        $param['roleType'] = $roleType; //1: 卖货团长（默认） 2:选品团长

        $this->giftCouponKey && $param['giftCouponKey'] = $this->giftCouponKey;

        $res = $jd_top->execute($param ,$this->accessToken);
        $res = objtoarr($res);
        return $res['returnType'];
    }

    /**
     * 新版转链接，支持转入自定义参数
     * @param $materialUrl
     * @param $couponUrl
     * @param $pid
     * @return mixed
     */
    public function transform($materialUrl ,$couponUrl='' ,$pid = ''){
        $this->getSceneFromUrl($materialUrl);
        !$pid && $pid = $this->pid;
        $pidInfo = explode("_",$pid);
        $unionId = $pidInfo[0];

        $jd_top = $this->_get_tool_union_top();
        $param['method'] = 'jd.union.open.promotion.byunionid.get';

        $param['promotionCodeReq']['materialId'] = $materialUrl;
        $couponUrl && $param['promotionCodeReq']['couponUrl'] = $couponUrl;
        $this->giftCouponKey && $param['promotionCodeReq']['giftCouponKey'] = $this->giftCouponKey;

        //        $param['promotionCodeReq']['subUnionId'] = '618_18_c35';
        $param['promotionCodeReq']['unionId'] = $unionId;
//        $param['promotionCodeReq']['positionId'] = $this->externalInfo;

        $param['promotionCodeReq']['sceneId'] = $this->sceneId;

        $res = $jd_top->execute($param);
        $prom = $res = objtoarr($res);

        $res = json_decode($res['getResult'],true);
        $shortUrl = data_get($res,'data.shortURL');
        empty($shortUrl) && logger()->debug("京东转链接".json_encode($param),$prom);
        return $res['data'] ?? [];
    }

    /**
     * 京东返回多个券
     * @param $couponList
     * @param $price
     * @return array
     */
    public function getMaxCoupon($couponList , $price){
        if(empty($couponList)){
            return [];
        }
        if(count($couponList) == 1 && ($couponList[0]['quota'] <= $price)){
            return $couponList[0];
        }
        $sort = array_column($couponList, 'discount');
        array_multisort($sort,SORT_DESC,$couponList);

        foreach ($couponList as $k=>$v){
            if($v['quota'] < $price){
                return $v;
            }
        }
        return [];
    }

    public function getSceneFromUrl($url){
        $this->setScene(1);
        if(strpos($url,'http')===false){
            return false;
        }
        // 返利场景分享出去的3.cn链接
        if(strpos($url,'3.cn')!==false){
            $this->setScene(2);
            return true;
        }
        //主站默认链接
        if(strpos($url , "item.m.jd.com")!==false || strpos($url , "item.jd.com")!==false){
            $this->setScene(2);
            return true;
        }
    }

    /**
     * 设置场景
     * @param $sceneId
     * @return $this
     */
    public function setScene($sceneId){
        $this->sceneId = $sceneId;
        return $this;
    }

    /**
     * @param mixed $pid
     * @return Jd
     */
    public function setPid($pid)
    {
        $this->pid = $pid;
        return $this;
    }

    public function setExternalInfo($uid = '', $usePlat = false ,$ext = []):Jd
    {
        $this->externalInfo = "";
        return $this;
    }

    /**
     * @param mixed $accessToken
     * @return Jd
     */
    public function setAccessToken($accessToken)
    {
        $this->accessToken = $accessToken;
        return $this;
    }

    /**
     * @param mixed $giftCouponKey
     * @return Jd
     */
    public function setGiftCouponKey($giftCouponKey)
    {
        $this->giftCouponKey = $giftCouponKey;
        return $this;
    }

    /**
     * 放弃数字ID
     * @param string $bool
     * @return $this
     */
    public function giveUpTbNumberId($bool = true):Jd
    {
        $this->giveUpNumberId = $bool;
        return $this;
    }
}